﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using WpfMesDemo2.Models;

namespace WpfMesDemo2.Data
{
    public class MesDbContext : DbContext
    {
        public DbSet<ProductionOrder> ProductionOrders { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<OrderProduct> OrderProducts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySql(
                    "server=localhost;database=mesdb;user=root;password=yuanlong",
                    ServerVersion.Parse("8.0.28-mysql"),
                    options => options.EnableRetryOnFailure(
                        maxRetryCount: 3,
                        maxRetryDelay: TimeSpan.FromSeconds(5),
                        errorNumbersToAdd: null)
                );
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 配置生产订单实体
            modelBuilder.Entity<ProductionOrder>()
                .HasKey(o => o.Id);

            modelBuilder.Entity<ProductionOrder>()
                .Property(o => o.OrderId)
                .IsRequired()
                .HasMaxLength(50);

            modelBuilder.Entity<ProductionOrder>()
                .HasMany(o => o.Products)
                .WithOne()
                .HasForeignKey(p => p.Id)
                .OnDelete(DeleteBehavior.Cascade);

            // 配置产品实体
            modelBuilder.Entity<Product>()
                .HasKey(p => p.Id);

            modelBuilder.Entity<Product>()
                .Property(p => p.ProductId)
                .IsRequired()
                .HasMaxLength(50);

            // 配置订单产品关联实体
            modelBuilder.Entity<OrderProduct>()
                .HasKey(op => op.Id);

            //modelBuilder.Entity<OrderProduct>()
            //    .HasOne(op => op.Order)
            //    .WithMany(o => o.Products)
            //    .HasForeignKey(op => op.OrderId)
            //    .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<OrderProduct>()
                .HasOne(op => op.Product)
                .WithMany()
                .HasForeignKey(op => op.ProductId)
                .OnDelete(DeleteBehavior.Cascade);

            // 添加全局查询过滤器，排除已删除的记录
            modelBuilder.Entity<ProductionOrder>()
                .HasQueryFilter(o => !o.IsDeleted);

            modelBuilder.Entity<Product>()
                .HasQueryFilter(p => !p.IsDeleted);
        }
    }
}
